/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.modules.system.service.impl;

import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.cspimp.psp.domain.Accident;
import me.zhengjie.modules.cspimp.psp.service.dto.AccidentDto;
import me.zhengjie.modules.system.domain.AreaManage;
import me.zhengjie.modules.system.domain.AreaMonitor;
import me.zhengjie.modules.system.domain.CameraMonitor;
import me.zhengjie.modules.system.domain.vo.AreaManageVo;
import me.zhengjie.modules.system.repository.AreaMonitorRepository;
import me.zhengjie.modules.system.repository.CameraMonitorRepository;
import me.zhengjie.modules.system.service.dto.AreaMonitorDto;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.system.repository.AreaManageRepository;
import me.zhengjie.modules.system.service.AreaManageService;
import me.zhengjie.modules.system.service.dto.AreaManageDto;
import me.zhengjie.modules.system.service.dto.AreaManageQueryCriteria;
import me.zhengjie.modules.system.service.mapstruct.AreaManageMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
 * @author 黄星星
 * @website https://docs.auauz.net
 * @description 服务实现
 * @date 2020-05-24
 **/
@Service
@RequiredArgsConstructor
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class AreaManageServiceImpl implements AreaManageService {

    private final AreaManageRepository areaManageRepository;
    private final AreaManageMapper areaManageMapper;
    private final CameraMonitorRepository cameraMonitorRepository;
    private final AreaMonitorRepository areaMonitorRepository;

    @Override
    public Map<String, Object> queryAll(AreaManageQueryCriteria criteria, Pageable pageable) {
        List<AreaManage> page = areaManageRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder));
        List<AreaManageDto> areaManageList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(page)) {
            for (AreaManage areaManage : page) {
                AreaManageDto areaManageDto = new AreaManageDto();
                BeanUtils.copyProperties(areaManage, areaManageDto);
                List<AreaMonitorDto> areaMonitorDtos = new ArrayList<>();
                List<AreaMonitor> areaMonitorList = areaMonitorRepository.getAllByAreaId(areaManage.getId());
                if (!CollectionUtils.isEmpty(areaMonitorList)) {
                    for (AreaMonitor areaMonitor : areaMonitorList) {
                        AreaMonitorDto areaMonitorDto = new AreaMonitorDto();
                        CameraMonitor cameraMonitor = cameraMonitorRepository.findById(areaMonitor.getCameraMonitorId()).orElse(null);
                        if (null != cameraMonitor) {
                            areaMonitorDto.setId(cameraMonitor.getId());
                            areaMonitorDto.setName(cameraMonitor.getName());
                        }
                        areaMonitorDtos.add(areaMonitorDto);
                    }

                }
                areaManageDto.setMonitorList(areaMonitorDtos);
                areaManageList.add(areaManageDto);
            }
        }
        return PageUtil.toPage(PageUtil.listPage(areaManageList, pageable));
    }

    @Override
    public List<AreaManageDto> queryAll(AreaManageQueryCriteria criteria) {
        return areaManageMapper.toDto(areaManageRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    public AreaManageDto findById(Long id) {
        AreaManage areaManage = areaManageRepository.findById(id).orElseGet(AreaManage::new);
        ValidationUtil.isNull(areaManage.getId(), "AreaManage", "id", id);
        return areaManageMapper.toDto(areaManage);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AreaManageDto create(AreaManageVo resources) {
        AreaManage areaManage = new AreaManage();
        BeanUtils.copyProperties(resources, areaManage);
        areaManage.setCid(0L);
        List<Long> areaMonitorList = resources.getAreaMonitorList();
        if (CollectionUtils.isEmpty(areaMonitorList)) {
            throw new BadRequestException("监控不能为空");
        }
        areaManageRepository.save(areaManage);
        //区域监控绑定关系
        for (Long id : areaMonitorList) {
            AreaMonitor areaMonitor = new AreaMonitor();
            areaMonitor.setCameraMonitorId(id);
            areaMonitor.setAreaId(areaManage.getId());
            areaMonitorRepository.save(areaMonitor);
        }

        return areaManageMapper.toDto(areaManage);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(AreaManageVo resources) {
        AreaManage areaManage = areaManageRepository.findById(resources.getId()).orElseGet(AreaManage::new);
        ValidationUtil.isNull(areaManage.getId(), "AreaManage", "id", resources.getId());
        BeanUtils.copyProperties(resources, areaManage);
        List<Long> areaMonitorList = resources.getAreaMonitorList();
        if (!CollectionUtils.isEmpty(areaMonitorList)) {
            //删除掉原来的绑定关系
            areaMonitorRepository.deleteByAreaId(resources.getId());
            for (Long id : areaMonitorList) {
                AreaMonitor areaMonitor = new AreaMonitor();
                areaMonitor.setAreaId(areaManage.getId());
                areaMonitor.setCameraMonitorId(id);
                areaMonitorRepository.save(areaMonitor);
            }

        }
        areaManageRepository.save(areaManage);
    }

    @Override
    @Transactional
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            areaManageRepository.deleteById(id);
            areaMonitorRepository.deleteByAreaId(id);
        }
    }

    @Override
    public void download(List<AreaManageDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (AreaManageDto areaManage : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("创建时间", areaManage.getCreateTime());
            map.put("更新时间", areaManage.getUpdateTime());
            map.put("创建者", areaManage.getCreateBy());
            map.put("更新者", areaManage.getUpdateBy());
            map.put("区域名称", areaManage.getAreaName());
            map.put("区域类型", areaManage.getAreaType());
//            map.put("区域监控", areaManage.getAreaMonitor());
            map.put("是否参加人数统计", areaManage.getJoinUserCount());
            map.put("关联围栏区域", areaManage.getRelFenceArea());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}